Formatting float column of Dataframe in Pandas

您所在的位置:网站首页 dataframe decimal Formatting float column of Dataframe in Pandas

Formatting float column of Dataframe in Pandas

2023-09-24 06:56| 来源: 网络整理| 查看: 265

While presenting the data, showing the data in the required format is also an important and crucial part. Sometimes, the value is so big that we want to show only desired part of this or we can say in some desired format.

Let’s see different methods of formatting integer column of Dataframe in Pandas.

Code #1 : Round off the column values to two decimal places.

# import pandas lib as pdimport pandas as pd  # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'],     'Expense': [ 21525220.653, 31125840.875, 23135428.768, 56245263.942]}  # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense'])  print("Given Dataframe :\n", dataframe)  # round to two decimal places in python pandaspd.options.display.float_format = '{:.2f}'.format  print('\nResult :\n', dataframe)

Output:

 Code #2 : Format ‘Expense’ column with commas and round off to two decimal places.

# import pandas lib as pdimport pandas as pd  # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'],        'Expense':[ 21525220.653, 31125840.875, 23135428.768, 56245263.942]}  # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense'])  print("Given Dataframe :\n", dataframe)  # Format with commas and round off to two decimal places in pandaspd.options.display.float_format = '{:, .2f}'.format  print('\nResult :\n', dataframe)

Output:

 Code #3 : Format ‘Expense’ column with commas and Dollar sign with two decimal places.

# import pandas lib as pdimport pandas as pd  # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'],        'Expense':[ 21525220.653, 31125840.875, 23135428.768, 56245263.942]}  # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense'])  print("Given Dataframe :\n", dataframe)  # Format with dollars, commas and round off# to two decimal places in pandaspd.options.display.float_format = '${:, .2f}'.format  print('\nResult :\n', dataframe)

Output:



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3